/**
 * Author : Fengyuan(Franklin) Zhang
 * Date : 2019/3/4
 * Description : Javascript Parser for MDL
 */
var React = require('react');
var Axios = require('axios');

var ModelSerTable = React.createClass({
    getInitialState : function () {
        return {
            loading : true,
            err : null,
            ms : null,
            init : true,
            type : this.props['data-type'],
            item : null,
            progress : false
        };
    },

    componentDidMount : function () {
        this.refresh();
    },

    refresh : function () {
        Axios.get(this.props['data-source']).then(
            data => {
                if(data.data.result == 'err')
                {
                    this.setState({loading : false, err : data.data.message});
                }
                else
                {
                    this.setState({loading : false, err : false, data : data.data.data});
                    if(this.state.init)
                    {
                        var options = {
                            //数据URL
                            "data": "/modelser/json/rmtall",
                            //载入数据的时候是否显示“正在加载中...”
                            "processing": true,
                            //是否显示分页
                            "bPaginate": true,
                            //每页显示条目数
                            "bLengthChange": true,
                            //排序
                            "bSort": true,
                            //排序配置
                            //"aaSorting": [[0, "desc"]],
                            //自适应宽度
                            "bAutoWidth": true,
                            //多语言配置
                            "oLanguage": {
                                "sLengthMenu": "_MENU_ records are displayed per page",
                                "sZeroRecords": "No record",
                                "sInfo": "No. _START_ to _END_ ， _TOTAL_ records at all",
                                "sInfoEmtpy": "No record",
                                "sInfoFiltered": " _MAX_ records at all)",
                                "sProcessing": "loading...",
                                "sSearch": "Search",
                                //多语言配置文件，可将oLanguage的设置放在一个txt文件中，例：Javascript/datatable/dtCH.txt
                                "sUrl": "",
                                "oPaginate": {
                                    "sFirst":    "First",
                                    "sPrevious": "Previous",
                                    "sNext":     "Next",
                                    "sLast":     "Last"
                                }
                            }
                        };
                        if(this.state.type == 'admin'){
                            options["aoColumnDefs"] = [ { "bSortable": false, "aTargets": [ 0 ] }];
                        }
                        //初始化完成
                        $('#modelservice-table').dataTable(options);
                        this.setState({init : false});
                    }

                }
            },
            err => {
                this.setState({loading : false, err : err});
            }
        );
    },

    startModelSerHandle : function (e, host, msid) {
        if(confirm('Open this model service?') == true)
        {
            if(host){
                Axios.put('/modelser/rmt/' + host + '/' + msid + '?ac=start').then(
                    data => {
                        this.refresh();
                    }
                );
            }
            else{
                Axios.put('/modelser/' + msid + '?ac=start').then(
                    data => {
                        this.refresh();
                    }
                );
            }
        }
    },

    stopModelSerHandle : function (e, host, msid) {
        if(confirm('Close this model service?') == true)
        {
            if(host){
                Axios.put('/modelser/rmt/' + host + '/' + msid + '?ac=stop').then(
                    data => {
                        this.refresh();
                    }
                );
            }
            else {
                Axios.put('/modelser/' + msid + '?ac=stop').then(
                    data => {
                        this.refresh();
                    }
                );
            }
        }
    },

    deleteModelSerHandle : function(e, host, msid) {
        if(confirm('Delete this model service?') == true)
        {
            if(host){
                Axios.delete('/modelser/rmt/' + host + '/' + msid ).then(
                    data => {
                        this.refresh();
                    }
                );
            }
            else{
                Axios.delete('/modelser/' + msid ).then(
                    data => {
                        this.refresh();
                    }
                );
            }
        }
    },

    openModelSerInfoHandle : function (e, host, msid) {
        window.location = '/modelser/' + msid;
    },

    uploadModelSer : function(e, host, msid){
        if(host){

        }
        else{
            window.open('/modelser/uploader/' + msid);
        }
    },

    openModelSerProHandle : function (e, host, msid) {
        window.open('/modelser/preparation/' + msid);
    },

    openRegisterDialogHandle : function (e, item) {
        this.setState({ item : item });
        $('#mdModelSerRegister').modal('show');
    },
    
    lockHandle : function(e, host, msid){
        if(confirm('Lock this model service?') == true)
        {
            if(host){
                Axios.put('/modelser/rmt/' + host + '/' + msid + '?ac=lock').then(
                    data => {
                        this.refresh();
                    }
                );
            }
            else{
                Axios.put('/modelser/' + msid + '?ac=lock').then(
                    data => {
                        this.refresh();
                    }
                );
            }
        }
    },

    unlockHandle : function(e, host, msid){
        if(confirm('Unlock this model service?') == true)
        {
            if(host){
                Axios.put('/modelser/rmt/' + host + '/' + msid + '?ac=unlock').then(
                    data => {
                        this.refresh();
                    }
                );
            }
            else{
                Axios.put('/modelser/' + msid + '?ac=unlock').then(
                    data => {
                        this.refresh();
                    }
                );
            }
        }
    },

    getCheckedList : function(){
        var inputs = $('input[name="ms_check"]:checked');
        if(inputs.length == 0){ return null; }
        var msids = [];
        for(var i = 0; i < inputs.length; i++){
            msids.push(inputs[i].value);
        };
        return msids;
    },

    batchStart : function(e){
        var msids = this.getCheckedList();
        if(msids == null){
            return;
        }
        if(confirm('Start these model services?')){
            Axios.put('/modelser/all?ac=start&msids=' + JSON.stringify(msids)).then(
                data => {
                    if(data.data.result == 'suc'){
                        this.refresh();
                    }
                },
                err => {}
            );
        }
    },

    batchStop : function(e){
        var msids = this.getCheckedList();
        if(msids == null){
            return;
        }
        if(confirm('Stop these model services?')){
            Axios.put('/modelser/all?ac=stop&msids=' + JSON.stringify(msids)).then(
                data => {
                    if(data.data.result == 'suc'){
                        this.refresh();
                    }
                },
                err => {}
            );
        }
    },

    batchLock : function(e){
        var msids = this.getCheckedList();
        if(msids == null){
            return;
        }
        if(confirm('Lock these model services?')){
            Axios.put('/modelser/all?ac=lock&msids=' + JSON.stringify(msids)).then(
                data => {
                    if(data.data.result == 'suc'){
                        this.refresh();
                    }
                },
                err => {}
            );
        }
    },

    batchUnlock : function(e){
        var msids = this.getCheckedList();
        if(msids == null){
            return;
        }
        if(confirm('Unlock these model services?')){
            Axios.put('/modelser/all?ac=unlock&msids=' + JSON.stringify(msids)).then(
                data => {
                    if(data.data.result == 'suc'){
                        this.refresh();
                    }
                },
                err => {}
            );
        }
    },

    checkAll : function(e){
        if($('#cb_checkall').is(':checked')){
            $('input[name="ms_check"]').attr("checked",'false');
        }
        else{
            $('input[name="ms_check"]').removeAttr("checked");
        }
    },

    render : function () {
        if(this.state.loading)
        {
            return (
                <span>loading...</span>
                );
        }
        if(this.state.err)
        {
            return (
                <span>Error : {JSON.stringify(this.state.err)}</span>
            );
        }
        var MsItems = [];
        var Heading = null;
        //! custom model services
        Heading = (
            <tr>
                <th>Name</th>
                <th>Version</th>
                <th>Type</th>
                <th>Permission</th>
                <th>Status</th>
                <th>Operation</th>
            </tr>
        );
        MsItems = this.state.data.map(function (item) {
            var status;
            var button;
            if(item.ms_status == 1)
            {
                status = (<span className="badge badge-success">Online</span>);
                button = (
                    <button className="btn btn-primary btn-xs" type="button" onClick={(e) => { this.openModelSerProHandle(e, 'custom', item._id) }} >
                        <i className="fa fa-retweet"> </i>Invoking
                    </button>);
            }
            else
            {
                status = (<span className="badge badge-defult">Offline</span>);
            }
            var permission = null;
            if(item.ms_permission == 1){
                permission = (<span className="label label-default tooltips" title="Auth" ><i className="fa fa-lock" ></i>&nbsp;Auth</span>);
            }
            else{
                permission = (<span className="label label-success tooltips" title="Public" ><i className="fa fa-unlock" ></i>&nbsp;Public</span>);
            }
            var name = item.ms_model.m_name;
            if(name.length > 25){
                name = name.substr(0, 25) + '...';
            }
            var type = item.ms_model.m_type;
            if(type == undefined || type == null){
                type = '';
            }
            if(type.length > 20){
                type = type.substr(0, 20) + '...';
            }
            return (
                <tr key={item._id}>
                    <td title={item.ms_model.m_name + '-' + item.ms_des}>{name}</td>
                    <td>{item.mv_num}</td>
                    <td title={item.ms_model.m_type}>{type}</td>
                    <td>{permission}</td>
                    <td>{status}</td>
                    <td>
                        <button className="btn btn-info btn-xs" type="button" onClick={ (e) =>
                        { this.openModelSerInfoHandle(e, 'custom', item._id ) } }  ><i className="fa fa-book"> </i>Detail</button>&nbsp;
                        {button}
                    </td>
                </tr>
            );
        }.bind(this));
        var ms_name = null;
        var ms_des = null;
        if(this.state.item){
            ms_name = this.state.item.ms_model.m_name;
            ms_des = this.state.item.ms_des;
        }
        var operation = null;
        return (
            <div>
                {operation}
                <table className="display table table-bordered table-striped" id="modelservice-table">
                    <thead>
                        {Heading}
                    </thead>
                    <tbody>
                        {MsItems}
                    </tbody>
                </table>
            </div>
        );
    }
});

module.exports = ModelSerTable;